<template>
  <div>
    <el-button type="info" @click="showDialog">{{ $t('编辑为组合商品') }}</el-button>
    <el-dialog
      append-to-body
      :title="$t('编辑为组合商品')"
      :visible.sync="dialog"
      width="1000px"
    >
      <div style="margin-top: -20px;">
        <span style="color: orange;">一个商品可能为多个子商品组合而成，请通过 Listing ID 或 SKU 搜索该商品的的子商品编辑为组合商品</span>
        <br>
        <span style="color: orange;">当前组合的子商品“组合数量”之和大于 1 确认提交则标记当前商品为组合商品，等于 1 则为非组合商品</span>
        <br>
        <span style="color: red;">*编辑为组合商品后，为避免超卖，组合商品和子商品出单消耗库存后都会自动同步更新美客多前台库存</span>
      </div>
      <div style="margin-top: 30px;">
        <span>当前组合的子商品：</span>
        <el-table
          :data="tableData"
          v-loading="loading"
          border
        >
          <el-table-column
            prop="goodsImage"
            :label="$t('table.productCover')"
            align="center"
            width="110"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="title"
            :label="$t('table.title')"
            align="center"
            min-width="200"
          >
            <template slot-scope="{row}">
              <el-tooltip placement="top" :content="row.title">
                <div class="title hidden-2">
                  {{ row.title }}
                </div>
              </el-tooltip>

              <div class="goods-attr">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                  style="color: #7F7F7F;"
                >
                {{attr.name}} : {{attr.value}}
                <span class="attr-link"> | </span>
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="goodsList"
            :label="$t('table.ListingIDAndSKU')"
            align="center"
            min-width="200"
          >
            <template v-slot="{row}">
              <div
                v-for="item in row.goodsList"
                :key="item.id"
              >
                <template v-if="!item.isTB && !item.isSystemLabel">
                  {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}
                </template>
                <!--<template v-if="item.isTB">-->
                <!--  {{$t('shipment.Not labeled')}}-->
                <!--</template>-->
                <!--<template v-else-if="item.isSystemLabel">-->
                <!--  {{$t('shipment.System label')}} ({{item.sku}})-->
                <!--</template>-->
                <!--<template v-else>-->
                <!--  {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}-->
                <!--</template>-->
              </div>
            </template>
          </el-table-column>

          <el-table-column
            :label="'组合数量'"
            align="center"
            width="200"
          >
            <template v-slot="scope">
              <template v-if="scope.$index === 0">
                <el-input-number :value="computedNum(scope.row)" :min="0" :max="999" @change="handleInputChange($event, scope.row)"></el-input-number>
              </template>
              <template v-else>
                <el-input-number :value="computedNum(scope.row)" :min="1" :max="999" @change="handleInputChange($event, scope.row)"></el-input-number>
              </template>
            </template>
          </el-table-column>

          <el-table-column
            :label="'操作'"
            align="center"
            width="150"
          >
            <template v-slot="scope">
              <template v-if="scope.$index === 0">
                <span>—</span>
              </template>
              <template v-else>
                <span style="color: red; cursor: pointer;" @click="removeCombinationGoods(scope.row)">移除</span>
              </template>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div style="margin-top: 30px;">
        <el-input size="small" style="width: 200px; margin-right: 10px; margin-bottom: 10px;" v-model="selectQueryParams.keyword" :placeholder="$t('common.searchForCompleteListingIDorSKU')"></el-input>
        <el-button size="small" type="primary" @click="search()">{{ $t('common.search') }}</el-button>
        <el-table
          :data="selectTableData"
          v-loading="selectLoading"
          border
        >
          <el-table-column
            prop="goodsImage"
            :label="$t('table.productCover')"
            align="center"
            width="110"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="title"
            :label="$t('table.title')"
            align="center"
            min-width="200"
          >
            <template slot-scope="{row}">
              <el-tooltip placement="top" :content="row.title">
                <div class="title hidden-2">
                  {{ row.title }}
                </div>
              </el-tooltip>

              <div class="goods-attr">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                  style="color: #7F7F7F;"
                >
                {{attr.name}} : {{attr.value}}
                <span class="attr-link"> | </span>
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="goodsList"
            :label="$t('table.ListingIDAndSKU')"
            align="center"
            min-width="200"
          >
            <template v-slot="{row}">
              <div
                v-for="item in row.goodsList"
                :key="item.id"
              >
                <template v-if="!item.isTB && !item.isSystemLabel">
                  {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}
                </template>
                <!--<template v-if="item.isTB">-->
                <!--  {{$t('shipment.Not labeled')}}-->
                <!--</template>-->
                <!--<template v-else-if="item.isSystemLabel">-->
                <!--  {{$t('shipment.System label')}} ({{item.sku}})-->
                <!--</template>-->
                <!--<template v-else>-->
                <!--  {{item.goodsId}} {{item.sku ? `(${item.sku})` : ''}}-->
                <!--</template>-->
              </div>
            </template>
          </el-table-column>

          <el-table-column
            :label="'操作'"
            align="center"
            width="150"
          >
            <template v-slot="scope">
              <span style="color: #1890ff; cursor: pointer;" @click="addCombinationGoods(scope.row)">添加</span>
            </template>
          </el-table-column>

        </el-table>
        <div class="page-wrap mgt10">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :current-page.sync="selectQueryParams.page"
            :page-size="selectQueryParams.pageSize"
            :total="selectTotal"
            @current-change="getSelectData"
          >
          </el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" :disabled="checkSubmit">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {stockList, saveCombinationGoods, getCombinationGoodsInfo} from "@/api/stock";
import {deepCopy} from "@/utils";

export default {
  name: "CombinationGoods",
  props:{
    suitId: {
      required: true,
      type: Number,
    }
  },
  data(){
    return {
      dialog: false,
      submitLoading: false,
      changeGoodsData: [],

      loading: false,
      queryParams: {
        selectSuitIds: [],
        isPacketGoods: false,
      },
      tableData: [],

      selectLoading: false,
      selectQueryParams: {
        page: 1,
        pageSize: 10,
        keyword: '',
        uncheckSuitIds: [],
        isPacketGoods: false,
        isCombinationGoods: 1,
      },
      selectTableData: [],
      selectTotal: 0,
    }
  },
  computed:{
    checkSubmit(){
      if (this.loading) {
        return true
      }
      if (this.changeGoodsData.length === 1 && this.changeGoodsData[0].id === this.suitId && this.changeGoodsData[0].num === 0) {
        // 删除
        return false
      }
      if (this.changeGoodsData.length <= 1) {
        return true
      }
      let num = 0
      this.changeGoodsData.forEach((item) => {
        num += item.num
      })
      let flag = true
      if (num > 1) {
        flag = false
      }
      return flag
    },
  },
  methods: {
    initialize(){
      this.loading = false
      this.submitLoading = false
      this.queryParams.selectSuitIds = []
      this.queryParams.isPacketGoods = false
      this.tableData = []
      this.selectLoading = false
      this.selectQueryParams.page = 1
      this.selectQueryParams.pageSize = 10
      this.selectQueryParams.keyword = ''
      this.selectQueryParams.uncheckSuitIds = []
      this.selectQueryParams.isPacketGoods = false
      this.selectQueryParams.isCombinationGoods = 1
      this.selectTableData = []
      this.selectTotal = 0
    },
    showDialog(){
      this.initialize()
      this.dialog = true
      this.getCombinationGoodsInfo()
    },
    getData(){
      this.loading = true
      stockList(this.queryParams)
        .then(res=>{
          this.loading = false
          this.tableData = deepCopy(res.data)
          this.changeComputedNum()
        })
    },
    changeComputedNum(){
      this.tableData.forEach((item, index) => {
        const num = index === 0 ? 0 : 1
        const goodsItem = this.changeGoodsData.find(v => v.id === item.id)
        if (goodsItem) {
          if (goodsItem.num < num) {
            goodsItem.num = num
          }
        } else {
          this.changeGoodsData.push({
            id: item.id,
            num: num,
          })
        }
      })
    },
    getCombinationGoodsInfo(){
      getCombinationGoodsInfo({'suitId': this.suitId})
        .then(res=>{
          this.changeGoodsData = res.data
          if (this.changeGoodsData.length > 0) {
            this.changeGoodsData.forEach(item => {
              this.queryParams.selectSuitIds.push(item.id)
            })
          } else {
            this.queryParams.selectSuitIds.push(this.suitId)
          }
          this.selectQueryParams.uncheckSuitIds = deepCopy(this.queryParams.selectSuitIds)
          this.getData()
          this.getSelectData()
        })
    },
    getSelectData(){
      this.selectLoading = true
      stockList(this.selectQueryParams)
        .then(res=>{
          this.selectLoading = false
          this.selectTableData = deepCopy(res.data)
          this.selectTotal = res.info.total
        })
    },
    search(){
      this.selectQueryParams.page = 1
      this.getSelectData()
    },
    addCombinationGoods(row){
      this.queryParams.selectSuitIds.push(row.id)
      this.selectQueryParams.uncheckSuitIds = deepCopy(this.queryParams.selectSuitIds)
      this.getData()
      this.getSelectData()
    },
    removeCombinationGoods(row){
      this.queryParams.selectSuitIds = this.queryParams.selectSuitIds.filter(id => id !== row.id)
      this.changeGoodsData = this.changeGoodsData.filter(id => id.id !== row.id)
      this.selectQueryParams.uncheckSuitIds = deepCopy(this.queryParams.selectSuitIds)
      this.getData()
      this.getSelectData()
    },
    handleInputChange(num, row) {
      const item = this.changeGoodsData.find(v => v.id === row.id)
      item.num = num
    },
    computedNum(row) {
      const item = this.changeGoodsData.find(v => v.id === row.id)
      return item ? item.num : 0
    },
    submitForm(){
      this.submitLoading = true
      const postData = {
        'goodsData': this.changeGoodsData,
        'suitId': this.suitId
      };
      saveCombinationGoods(postData)
        .then(res=>{
          this.submitLoading = false
          if(res.error === 0){
            this.$successMessage(res.message)
            this.dialog = false
            this.$emit('submitForm');
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
  },
}
</script>

<style scoped lang="scss">

</style>
